import serial
import pandas as pd

# 创建串口连接
ser = serial.Serial(
    port="COM14",  # 替换为你的串口名称
    baudrate=115200,  # 替换为你的波特率
    parity=serial.PARITY_NONE,  # 替换为你的校验位
    stopbits=serial.STOPBITS_ONE,  # 替换为你的停止位
    bytesize=serial.EIGHTBITS,  # 替换为你的数据位数
    timeout=1,  # 设置超时时间
)


def pd_toExcel(data, filename):
    batterys = []
    voltages = []
    temperatures = []
    for item in data:
        battery, voltage, temperature = item.split(",")
        batterys.append(int(battery))
        voltages.append(int(voltage))
        temperatures.append(int(temperature))
    df = pd.DataFrame(
        {
            "battery": batterys,
            "voltage": voltages,
            "temperature": temperatures,
        }
    )
    df.to_excel(filename, index=False)


try:
    index = 0
    result = []
    while index < 10000:
        ser.write(b"AT+HMBATTERY?\r\n")  # 发送 AT 命令

        try:
            data = ser.readline().decode("utf-8").strip()
            if data:
                print(f"Received: {data}")
                # 以 OK 结尾的字符串，
                if data.endswith("OK"):
                    index += 1
                if data.startswith("+HMBATTERY:"):
                    # 提取百分比部分
                    percent = data.split(":")[1].strip()
                    print(f"{index}: Percentage: {percent}")
                    result.append(percent)
        except:
            print("Error: Could not decode data")
        # 等待一段时间，避免过于频繁地读取
        import time

        time.sleep(0.05)
    pd_toExcel(result, "battery.xlsx")

except Exception as e:
    print(f"Error: {e}")
finally:
    ser.close()  # 确保在程序结束时关闭串口连接
